import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getProfileApi } from '@/apis/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/LoginPage.vue'),
      meta: {
        hidden: true,
      },
    },
    {
      path: '/',
      redirect: '/preview',
      meta: { hidden: true },
    },
    {
      path: '/preview',
      name: 'preview',
      component: () => import('@/layouts/MainLayout.vue'),
      children: [
        {
          path: '',
          component: () => import('@/views/preview/PreviewPage.vue'),
          meta: { title: '数据概览', icon: 'system' },
        },
      ],
    },
    {
      path: '/article',
      name: 'article',
      component: () => import('@/layouts/MainLayout.vue'),
      children: [
        {
          path: '',
          component: () => import('@/views/article/ArticlePage.vue'),
          meta: { title: '内容管理', icon: 'system' },
        },
      ],
    },
    {
      path: '/publish',
      name: 'publish',
      component: () => import('@/layouts/MainLayout.vue'),
      children: [
        {
          path: '',
          component: () => import('@/views/publish/PublishPage.vue'),
          meta: { title: '发布文章', icon: 'system' },
        },
      ],
    },
  ],
})

// 白名单
const whiteList = ['/login']

// 导航守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  if (userStore.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!userStore.profile.id) {
        // 1、获取用户信息
        const res = await getProfileApi()
        await userStore.setUser(res)
      }

      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

router.afterEach(() => {})
export default router
